package com.ddshuai.easy;

/**
 * 描述 新通教育
 *
 * @author ddshuai
 * @date 2018-10-17 08:56
 * <p>
 * 给定一个整数，将其转化为7进制，并以字符串形式输出。
 * <p>
 * 输入: 100
 * 输出: "202"
 * <p>
 * 输入: -7
 * 输出: "-10"
 * <p>
 * 注意: 输入范围是 [-1e7, 1e7]
 **/
public class ConvertToBase7 {

    /**
     * 效率一般
     * 241 / 241 个通过测试用例
     * 57.18%
     * 执行用时：47 ms
     * @param num
     * @return
     */
    public static String convertToBase7(int num) {
        String res = "";
        if (Math.abs(num) < 7){
            return num+"";
        }
        int div = Math.abs(num) / 7;
        int mod = Math.abs(num) % 7;
        res += mod;
        while (div >= 7) {
            mod = div % 7;
            div = div / 7;

            res = mod + res;
        }
        res = div +res;
        if (num<0){
            res = "-"+res;
        }
        return res;
    }

    /**
     * 63.9%
     * @param num
     * @return
     */
    public static String convertToBase7_2(int num) {
        int temp = num;
        if(temp<0) {
            temp = temp*-1;
        }
        String s = "";
        if(temp==0) {
            return "0";
        }
        while(temp!=0){
            s=temp%7 + s;
            temp=temp/7;
        }
        if(num<0) {
            s="-"+s;
        }
        //浪费性能
       // s=new StringBuffer(s).reverse().toString();
        return s;
    }

    public static String jdk(int i){
        char[] digits = {
                '0' , '1' , '2' , '3' , '4' , '5' ,
                '6' , '7' , '8' , '9' , 'a' , 'b' ,
                'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
                'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
                'o' , 'p' , 'q' , 'r' , 's' , 't' ,
                'u' , 'v' , 'w' , 'x' , 'y' , 'z'
        };
        int radix = 7;


        char buf[] = new char[33];
        boolean negative = (i < 0);
        int charPos = 32;

        if (!negative) {
            i = -i;
        }

        while (i <= -radix) {
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];

        if (negative) {
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (33 - charPos));
    }


    public static void main(String[] args) {
        System.out.println(jdk(100));
        System.out.println(jdk(7));
        System.out.println(jdk(77));
        System.out.println(jdk(-77));
        System.out.println(jdk(-7));
    }
}
